package com.distribution.system.controller;


import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.utils.poi.ExcelUtil;
import com.distribution.system.domain.dto.AgentDTO;
import com.distribution.system.domain.dto.AgentProxyProductDTO;
import com.distribution.system.domain.dto.UpdateSubAgentCommissionByDeductPercentDTO;
import com.distribution.system.domain.entity.CmccDaProduct;
import com.distribution.system.domain.entity.CmccDaProxyProductManage;
import com.distribution.system.domain.req.CmccDaProductListReq;
import com.distribution.system.domain.req.ProductCollectReq;
import com.distribution.system.domain.req.ProxyProductManageListReq;
import com.distribution.system.domain.req.ProxyProductPromotionFlagUpdateReq;
import com.distribution.system.domain.vo.ProductProxyVO;
import com.distribution.system.domain.bo.CardProxyVOExportBO;
import com.distribution.system.domain.vo.ProxyProductVO;
import com.distribution.system.domain.dto.UpdateDaProxyProductDTO;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.CmccDaProxyProductManageService;
import com.distribution.system.service.ISysUserService;
import com.distribution.system.utils.convert.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 *
 * 代理卡信息表(CmccDaProxyCardManage)表控制层
 *
 * @since 2023-05-21 16:08:28
 */
@RestController
@RequestMapping(value = "/cmccDaProxyCardManage")
@Slf4j
public class CmccDaProxyProductManageController extends BaseController {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    ISysUserService userService;

    @Resource
    CmccDaProxyProductManageService cmccDaProxyProductManageService;

    /**
     * 收藏商品
     */
    @PostMapping("/collectProduct")
    public AjaxResult collectProduct(@RequestBody ProductCollectReq productCollectReq) {
        //System.out.println("收藏productCollectReq = " + productCollectReq);
        cmccDaProxyProductManageService.lambdaUpdate().set(CmccDaProxyProductManage::getCollectFlag, "1")
                .eq(CmccDaProxyProductManage::getProductCode, productCollectReq.getProductCode())
                .eq(CmccDaProxyProductManage::getUserId, getUserId()).update();
        return AjaxResult.success();
    }
    /**
     * 收藏商品
     */
    @PostMapping("/cancelCollectProduct")
    public AjaxResult cancelCollectProduct(@RequestBody ProductCollectReq productCollectReq) {
        //System.out.println("取消收藏ProductCollectReq productCollectReq");
        cmccDaProxyProductManageService.lambdaUpdate().set(CmccDaProxyProductManage::getCollectFlag, "0")
                .eq(CmccDaProxyProductManage::getProductCode, productCollectReq.getProductCode())
                .eq(CmccDaProxyProductManage::getUserId, getUserId()).update();
        return AjaxResult.success();
    }

    /**
     * 更新卡佣金配置
     * @param updateDaProxyProductDTO 修改代理卡配置信息
     * @return 响应结果
     */
    @PostMapping(value = "/updateAgentProxyCard")
    public AjaxResult updateAgentProxyCard(@RequestBody UpdateDaProxyProductDTO updateDaProxyProductDTO){
        cmccDaProxyProductManageService.updateAgentProxyProduct(updateDaProxyProductDTO);
        return success();
    }

    /**
     * 一键隐藏多条选中代理卡
     */
    @PostMapping(value = "/hideAgentProxyProductStatus")
    public AjaxResult hideAgentProxyProductStatus(@RequestBody UpdateDaProxyProductDTO updateDaProxyCardDTO){
        Long userId = updateDaProxyCardDTO.getUserId();
        List<String> cardIdList = updateDaProxyCardDTO.getProductCodeList();
        cmccDaProxyProductManageService.updateAgentProxyProductStatus(userId, cardIdList, 0);
        return success();
    }
    /**
     * 一键显示多条选中代理卡
     */
    @PostMapping(value = "/showAgentProxyProductStatus")
    public AjaxResult showAgentProxyProductStatus(@RequestBody UpdateDaProxyProductDTO updateDaProxyCardDTO){
        Long userId = updateDaProxyCardDTO.getUserId();
        List<String> cardIdList = updateDaProxyCardDTO.getProductCodeList();
        cmccDaProxyProductManageService.updateAgentProxyProductStatus(userId, cardIdList, 1);
        return success();
    }

    /**
     * 查找我的卡佣金配置
     * @param agentProxyProductDTO 代理卡管理
     * @return 响应结果
     */
    @PostMapping(value = "/selectAgentProxyCard")
    public AjaxResult selectAgentProxyCard(@RequestBody AgentProxyProductDTO agentProxyProductDTO){
        ProxyProductVO cmccDaProxyCardManageList = cmccDaProxyProductManageService.selectAgentProxyProductVO(agentProxyProductDTO);
        return success(cmccDaProxyCardManageList);
    }


    /**
     * 查找我的卡佣金配置
     */
    @PostMapping(value = "/selectCardProxy")
    public TableDataInfo selectProxyProductList(@RequestBody ProxyProductManageListReq proxyProductManageListReq){
        startPage();
        List<ProductProxyVO> productProxyVO = cmccDaProxyProductManageService.selectProxyProductList(proxyProductManageListReq);
        return getDataTable(productProxyVO);
    }

    /**
     * 查找我的卡佣金配置
     */
    @PostMapping(value = "/selectCardProxyExport")
    public void selectCardProxyExport(HttpServletResponse response, ProxyProductManageListReq proxyProductManageListReq){
        List<ProductProxyVO> productProxyVO = cmccDaProxyProductManageService.selectProxyProductList(proxyProductManageListReq);
        List<CardProxyVOExportBO> cmccDaOrderExportBOS = BeanUtils.copyBeanCollection(CardProxyVOExportBO.class, productProxyVO);
        ExcelUtil<CardProxyVOExportBO> util = new ExcelUtil<>(CardProxyVOExportBO.class);
        util.exportExcel(response, cmccDaOrderExportBOS, "卡佣金配置");
    }

    /**
     * 总运营设置下级佣金
     */
    @PostMapping(value = "/updateDownAgentProxyCard")
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    public AjaxResult operationSetAllAgentCommission(@RequestBody UpdateDaProxyProductDTO updateDaProxyProductDTO){
        UpdateSubAgentCommissionByDeductPercentDTO updateSubAgentCommissionByDeductPercentDTO = new UpdateSubAgentCommissionByDeductPercentDTO();
        updateSubAgentCommissionByDeductPercentDTO.setCurrentSysUser(sysUserMapper.selectUserById(getUserId()));
        updateSubAgentCommissionByDeductPercentDTO.setProductCode(updateDaProxyProductDTO.getProductCode());
        updateSubAgentCommissionByDeductPercentDTO.setMyCommission(updateDaProxyProductDTO.getDownCommission());
        cmccDaProxyProductManageService.updateSubAgentCommissionByDeductPercent(updateSubAgentCommissionByDeductPercentDTO);
        return success();
    }

    /**
     * 一二级代理设置下级佣金
     */
    @PostMapping(value = "/updateDownAgentProxyProductCommission")
    @PreAuthorize("@ss.hasAnyRoles('firstLevelAgent,secondLevelAgent')")
    public AjaxResult updateDownAgentProxyProductCommission(@RequestBody UpdateDaProxyProductDTO updateDaProxyProductDTO){
        String productCode = updateDaProxyProductDTO.getProductCode();
        BigDecimal downCommission = updateDaProxyProductDTO.getDownCommission();
        SysUser currentSysUser = sysUserMapper.selectUserById(getUserId());
        if (currentSysUser.getRoleId() != 100L && currentSysUser.getRoleId() != 101L){
            return error("当前角色无法设置下级佣金！");
        }
        // 所有下级代理
        AgentDTO agentDTO = new AgentDTO();
        agentDTO.setParentId(getUserId());
//        List<SysUser> allSubAgentList = sysUserMapper.selectAllUserListByParentId(agentDTO);
        List<SysUser> allSubAgentList = userService.selectUserListByParentId(agentDTO);
        // 所有下一级代理
        List<SysUser> subFirstAgentList = allSubAgentList;
        if (currentSysUser.getRoleId() == 100L){// 一级代理
            subFirstAgentList = allSubAgentList.stream().filter(f -> f.getRoleId() == 101L).collect(Collectors.toList());
        }
        List<Long> subAgentUserIdList = subFirstAgentList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        cmccDaProxyProductManageService.lambdaUpdate()
                .set(CmccDaProxyProductManage::getCommission, downCommission)
                .set(CmccDaProxyProductManage::getUpdateTime, new Date())
                .set(CmccDaProxyProductManage::getUpdateUserId, currentSysUser.getUserId())
                .set(CmccDaProxyProductManage::getUpdateUserName, currentSysUser.getUserName())
                .eq(CmccDaProxyProductManage::getProductCode, productCode)
                .in(CmccDaProxyProductManage::getUserId, subAgentUserIdList)
                .update();
        // 一级代理的下级还有可能有二级代理
        if (currentSysUser.getRoleId() == 100L){// 一级代理
            List<SysUser> subSecondAgentList = allSubAgentList.stream().filter(f -> f.getRoleId() == 102L).collect(Collectors.toList());
            if (subSecondAgentList.isEmpty()) return success();
            List<Long> subSecondAgentUserIdList = subSecondAgentList.stream().map(SysUser::getUserId).collect(Collectors.toList());
            List<CmccDaProxyProductManage> subSecondAgentProductManageList = cmccDaProxyProductManageService.lambdaQuery()
                    .eq(CmccDaProxyProductManage::getProductCode, productCode)
                    .in(CmccDaProxyProductManage::getUserId, subSecondAgentUserIdList)
                    .list();
            if (subSecondAgentProductManageList.isEmpty()) return success();
            subSecondAgentProductManageList.forEach(proxyProductManage -> {
                SysUser sysUser = subSecondAgentList.stream().filter(f -> Objects.equals(f.getUserId(), proxyProductManage.getUserId())).collect(Collectors.toList()).get(0);
                BigDecimal currentCommission = cmccDaProxyProductManageService.getCommissionByDeduct(downCommission, sysUser.getSupDeduct());
                if (proxyProductManage.getCommission().compareTo(currentCommission) != 0){
                    proxyProductManage.setCommission(currentCommission);
                    proxyProductManage.setUpdateTime(new Date());
                    proxyProductManage.setUpdateUserId(sysUser.getUserId().intValue());
                    proxyProductManage.setUpdateUserName(getUsername());
                }
            });
            cmccDaProxyProductManageService.updateBatchById(subSecondAgentProductManageList);
        }
        return success();
    }

    /**
     * 统一佣金
     */
    @PostMapping(value = "/unifiedCommission")
    public AjaxResult unifiedCommission(@RequestBody CmccDaProduct cmccDaProduct){
        cmccDaProxyProductManageService.unifiedCommission(cmccDaProduct);
        return success();
    }

    @PostMapping("/changeProxyProductPromotionFlag")
    public AjaxResult changeProxyProductPromotionFlag(@RequestBody ProxyProductPromotionFlagUpdateReq promotionFlagUpdateReq){
        cmccDaProxyProductManageService.lambdaUpdate()
                .eq(CmccDaProxyProductManage::getProductCode, promotionFlagUpdateReq.getProductCode())
                .eq(CmccDaProxyProductManage::getUserId, getUserId())
                .set(CmccDaProxyProductManage::getPromotionFlag, promotionFlagUpdateReq.getPromotionFlag())
                .update();
        return success();
    }

    @PostMapping(value = "/getProxyProductManage")
    public AjaxResult getProxyProductManage(@RequestBody AgentProxyProductDTO agentProxyProductDTO){
        CmccDaProxyProductManage proxyProductManage = cmccDaProxyProductManageService.lambdaQuery()
                .eq(CmccDaProxyProductManage::getUserId, agentProxyProductDTO.getUserId())
                .eq(CmccDaProxyProductManage::getProductCode, agentProxyProductDTO.getProductCode()).one();
        return success(proxyProductManage);
    }
}
